package leetcode.day_2021_03_15_2021_03_21;

import java.util.Arrays;

/**
 * 66. 加一
 * https://leetcode-cn.com/problems/plus-one/
 * [9,9]
 */
public class LeetCode0066 {

    public static int[] plusOne(int[] digits) {
        int len = digits.length;
        int[] newDigits;
        // 判断新数组的长度
        if (len>0 && ((digits.length==1&&digits[0]==9) || (digits[0]==9&&digits[1]+1>=10))) {
            newDigits = new int[len+1];
        } else {
            newDigits = new int[len];
        }


        int enterOne = 0;
        for (int i=len-1; i>=0; i--) {
            int num;
            if (i==len-1) {
                num = digits[i] + 1 + enterOne;
            } else {
                num = digits[i] + enterOne;
            }

            // 用完，重新归0
            enterOne = 0;
            if(num/10 != 0) {
                enterOne = num/10;
                newDigits[i] = num % 10;
            } else {
                newDigits[i] = num;
            }
        }
        return newDigits;
    }

    public static int[] plusOne2(int[] digits) {
        for (int i = digits.length - 1; i >= 0; i--) {
            digits[i]++;
            digits[i] = digits[i] % 10;
            if (digits[i] != 0) {
                return digits;
            }
        }
        digits = new int[digits.length + 1];
        digits[0] = 1;
        return digits;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(plusOne2(new int[]{1, 2, 3})));
//        System.out.println(Arrays.toString(plusOne(new int[]{9, 9, 9})));
//        System.out.println(Arrays.toString(plusOne(new int[]{9})));
    }
}
